package com.beiding.cprender;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/*
    工厂类
    该类用于创建模板对象,插件对象已经Handler对象
 */
public class F {


    private static Map<File, CPTemplateEngine> engineMap = new HashMap<>();

    public static <T> T get(Class<T> type) {
        try {

            Object o = null;
            if (CpTemplate.class.isAssignableFrom(type)) {
                File rootFile = ClasspathUtils.getRootFile(type);
                o=engineMap.computeIfAbsent(rootFile, CPTemplateEngine::new).getTemplate((Class<CpTemplate>) type);
            } else if (CpPlugin.class.isAssignableFrom(type)) {
                File rootFile = ClasspathUtils.getRootFile(type);
                o= engineMap.computeIfAbsent(rootFile, CPTemplateEngine::new).getPlugin((Class<CpPlugin>) type);
            } else if (CpHandler.class.isAssignableFrom(type)) {
                File rootFile = ClasspathUtils.getRootFile(type);
                o = engineMap.computeIfAbsent(rootFile, CPTemplateEngine::new).getHandler((Class<CpHandler>) type);
            }

            if (o == null) {
                throw new RuntimeException("获取不到对象:" + type);
            }

            return (T) o;
        } catch (Exception e) {
            throw new RuntimeException("模板初始化失败:" + type);
        }
    }


    public static CPTemplateEngine getEngine(Class<? extends CpExporter> exporter) {
        try {
            File rootFile = ClasspathUtils.getRootFile(exporter);
            return engineMap.computeIfAbsent(rootFile, CPTemplateEngine::new);
        } catch (Exception e) {
            throw new RuntimeException("导出器初始化失败:" + exporter);
        }
    }
}
